package com.geostar.constructionland.statistics.service.impl;

import com.geostar.constructionland.common.entity.statistics.UnifiedDataQueryConfig;
import com.geostar.constructionland.statistics.dao.DataQueryDao;
import com.geostar.constructionland.statistics.mapping.QueryMappedStatement;
import com.geostar.constructionland.statistics.service.IDataQueryService;
import com.geostar.constructionland.statistics.service.IUnifiedDataQueryConfigService;
import com.geostar.constructionland.statistics.service.factory.MappedStatementFactory;
import com.geostar.constructionland.statistics.service.factory.PostDataProcessFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author makoto_zhu
 * @Date 2020-11-18 11:42:59
 * @Description 数据查询接口处理类
 **/
@Service
public class DataQueryServiceImpl implements IDataQueryService {

    @Resource
    private DataQueryDao dataQueryDao;

    @Resource
    private IUnifiedDataQueryConfigService unifiedDataQueryConfigService;

    @Resource
    private MappedStatementFactory mappedStatementFactory;

    @Resource
    private PostDataProcessFactory postDataProcessFactory;

    private QueryMappedStatement queryMappedStatement;

    @Override
    public List<Map<String, Object>> queryData(String uniqueQueryId, String paramJson) throws Exception {
        // 根据uniqueQueryId查询配置实体
        UnifiedDataQueryConfig unifiedDataQueryConfig = unifiedDataQueryConfigService.getOne(uniqueQueryId);
        if (Objects.isNull(unifiedDataQueryConfig)) {
            throw new IllegalArgumentException("UniqueQueryId cannot be found , Please check it do exist");
        }

        // 重新覆盖配置文件中默认的查询参数
        unifiedDataQueryConfig.setParams(paramJson);

        // 根据配置实体组装QueryMappedStatement
        queryMappedStatement = mappedStatementFactory.create(unifiedDataQueryConfig);

        // 执行查询
        List<Map<String, Object>> result = dataQueryDao.execute(queryMappedStatement);

        // 查询后置数据处理
        postDataProcessFactory.process(queryMappedStatement, result);
        return result;
    }
}
